package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.*;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 商品
 * @author: xxx
 * @create: 2021/7/19 09:30
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderService service;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommissionService commissionService;

    @Autowired
    private GetCreditsService getCreditsService;
    @Autowired
    private RedisUtil redisUtil;
    Lock lock = new ReentrantLock();
    private Integer goodsNums = 2;

    /**
     * @param map
     * @description: 下单
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("saveOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result saveOrder(@RequestBody Map<String, Object> map) {
        lock.lock();
        try {

            Map<String, Object> goodsMap = goodsService.getById(map);
            if (goodsMap.get("added").toString().equals("2")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                map.put("orderSn", simpleDateFormat.format(new Date()));
                map.put("price", goodsMap.get("price"));
                map.put("goodsId", goodsMap.get("id"));
                map.put("buyerId", TokenTool.getUserId());
                map.put("userId", goodsMap.get("uId"));
                map.put("id", IDTool.getUUID32());
                service.saveOrder(map);
                goodsMap.put("added", 3);//已售
                goodsService.update(goodsMap);
            } else {
                return ResultUtil.error(-500, "活动太火爆了");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-500, "活动太火爆了");
        } finally {
            lock.unlock();
        }
        return ResultUtil.success();
    }

    /**
     * @param
     * @description: 预售
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("preOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result preOrder(@RequestBody Map<String, Object> map) {
        lock.lock();
        try {
            String keyDate = "preOrder:" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ":" + TokenTool.getUserId();
            if (redisUtil.get(keyDate) != null) {
                String key = "preOrder:buyNums";
                if (redisUtil.get(key) != null) {
                    goodsNums = Integer.parseInt(redisUtil.get(key).toString());
                }
                if (Integer.parseInt(redisUtil.get(keyDate).toString()) >= goodsNums) {
                    return ResultUtil.error(-500, "当日只能抢购" + goodsNums + "个商品");
                }
            }
            map.put("userId", TokenTool.getUserId());
            Map<String, Object> mapTime = new HashMap<>();
            Map<String, Object> mapVip = userService.selectVipByUserId(TokenTool.getUserId());
            if (mapVip != null && mapVip.get("vip").toString().equals("1")) {
//                if (TokenTool.getVip() != null && TokenTool.getVip().equals("1")){
                mapTime.put("id", "1");//会员抢购时间
                Map<String, Object> time = goodsService.getTimeById(mapTime);
                map.put("startTime", time.get("startTime"));
                map.put("endTime", time.get("endTime"));
            } else {
                mapTime.put("id", "2");//普通抢购时间
                Map<String, Object> time = goodsService.getTimeById(mapTime);
                map.put("startTime", time.get("startTime"));
                map.put("endTime", time.get("endTime"));
            }
            List<Map<String, Object>> list = goodsService.getPreSale(map);
            if (list != null && list.size() > 0) {
                Map<String, Object> goodsMap = list.get(0);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                map.put("orderSn", simpleDateFormat.format(new Date()));
                map.put("price", goodsMap.get("price"));
                map.put("goodsId", goodsMap.get("id"));
                map.put("buyerId", TokenTool.getUserId());
                map.put("userId", goodsMap.get("uId"));
                map.put("id", IDTool.getUUID32());
                service.saveOrder(map);
                if (redisUtil.get("preOrder:" + TokenTool.getUserId()) != null) {
                    int num = Integer.parseInt(redisUtil.get(keyDate).toString());
                    redisUtil.set(keyDate, String.valueOf(num + 1), 24L, TimeUnit.HOURS);
                } else {
                    redisUtil.set(keyDate, "1", 24L, TimeUnit.HOURS);
                }
            } else {
                return ResultUtil.error(-500, "该价格区间商品已抢完");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-500, "活动太火爆了");
        } finally {
            lock.unlock();
        }
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getById")
    public Result getById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getById(map));
    }

    /**
     * @param json
     * @description: 获取购买记录
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("orderList")
    public Result orderList(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);

        if (jsonObject.get("type").toString().equals("1")) {
            jsonObject.put("status", "1");
            jsonObject.put("buyerId", TokenTool.getUserId());
        } else if (jsonObject.get("type").toString().equals("2")) {
            jsonObject.put("statusNot", "3");
            jsonObject.put("userId", TokenTool.getUserId());
        } else {
            jsonObject.put("buyerId", TokenTool.getUserId());
            jsonObject.put("status", "2");
        }
        jsonObject.remove("type");

//        jsonObject.put("studioId", TokenTool.getStudioId());
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getWeekList(jsonObject);
        int total = service.getWeekCount(jsonObject);
        return ResultUtil.successPage(list, total);
    }

    /**
     * @param
     * @description: 支付
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("payOrder")
    public Result payOrder(@RequestBody Map<String, Object> map) {
        Map<String, Object> order = service.getById(map);
        if (order != null && order.get("status").toString().equals("1")) {
            if (order.get("images") != null) {
                Map<String, Object> orderMap = new HashMap<>();
                orderMap.put("status", 2);
                orderMap.put("id", order.get("id"));
                orderMap.put("payDate", new Date());
                service.update(orderMap);
            } else {
                return ResultUtil.error(-500, "请上传支付凭证");
            }

        } else {
            return ResultUtil.error(-500, "该状态不允许支付");
        }


        return ResultUtil.success();
    }

    /**
     * @param
     * @description: 上传支付凭证
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("payImages")
    public Result payImages(@RequestBody Map<String, Object> map) {
        String images = map.get("images").toString();
        Map<String, Object> order = service.getById(map);
        if (order != null && order.get("status").toString().equals("1")) {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("id", order.get("id"));
            orderMap.put("images", images);
            service.update(orderMap);
        } else {
            return ResultUtil.error(-500, "该状态不允许支付");
        }


        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 确认订单
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/11 15:49
     */
    @RequestMapping("confirmOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result confirmOrder(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapOrder = service.getById(map);
        if (!mapOrder.get("status").toString().equals("3") && !mapOrder.get("status").toString().equals("4")) {
            if (mapOrder.get("userId").toString().equals(TokenTool.getUserId())) {
                // 更新商品
                map.put("status", 3);
                service.update(map);
                // 更新订单
                Map<String, Object> mapNew = new HashMap<>();
                mapNew.put("id", mapOrder.get("goodsId"));
                mapNew.put("buyPrice", mapOrder.get("price"));
                mapNew.put("buyTime", mapOrder.get("createDate"));
                mapNew.put("uId", mapOrder.get("buyerId"));
                mapNew.put("added", 2);
                goodsService.update(mapNew);

                // 订单交易完成后，给介绍人0.5%的积分 --- new
                Map<String, Object> yqrUser = new HashMap<>();
                yqrUser.put("id", mapOrder.get("buyerId"));
                // 根据id查询当前用户信息
                Map<String, Object> meData = userService.getById(yqrUser);
                // 如果这个人有邀请人 就给邀请人 0.5% 的提成
                String Pid = (String) meData.get("pid");
                if (Pid.length() > 0) {
                    Map<String, Object> mapPid = new HashMap<>();
                    mapPid.put("pid", meData.get("pid"));
                    // 根据pid查出用户的邀请人
                    Map<String, Object> uData = userService.getByPid(mapPid);
                    // 计算积分0.5%是多少
                    BigDecimal money = new BigDecimal(Double.valueOf(mapOrder.get("price").toString()));//交易金额
                    BigDecimal td = new BigDecimal(Double.valueOf(0.005));//提点
                    BigDecimal tdMoney = money.multiply(td).setScale(2, BigDecimal.ROUND_HALF_UP);//乘法四舍五入保留两位小数
                    // 查出介绍人的积分账单
                    Map<String, Object> params = new HashMap();
                    params.put("id", meData.get("pid"));
                    Map<String, Object> UserCredits = getCreditsService.getMyCredits(params);
                    // 计算剩余积分 账户积分+提成
                    BigDecimal totalC = new BigDecimal(Double.valueOf(UserCredits.get("total").toString()));  // 账户目前可用积分 total
                    BigDecimal tcMoney = totalC.add(tdMoney).setScale(2, BigDecimal.ROUND_HALF_UP);// 加法四舍五入保留两位小数

                    // 存储积分信息
                    Map<String, Object> creditMap = new HashMap<>();
                    // mapOrder.get("buyerId")
                    creditMap.put("id", IDTool.getUUID32());
                    creditMap.put("userId", uData.get("id"));
                    // 邀请人信息
                    creditMap.put("userName", uData.get("nikeName"));
                    creditMap.put("userPhone", uData.get("name"));
                    // 其他信息
                    creditMap.put("putawayShopName", mapOrder.get("goodsName"));
                    creditMap.put("putawayShopPrice", mapOrder.get("price"));
                    creditMap.put("putawayShopSn", mapOrder.get("orderSn"));
                    // tcMoney
                    creditMap.put("getCredits", tdMoney);
                    creditMap.put("accountCredits", tcMoney);  // 账户剩余积分
                    getCreditsService.saveInviteAdd(creditMap);
                }
                // 更新商品状态为已出售
                Map<String, Object> mapEarnings = new HashMap<>();
                mapEarnings.put("goodsId", mapOrder.get("goodsId"));
                mapEarnings.put("userId", mapOrder.get("userId"));
                mapEarnings.put("status", 2);
                mapEarnings.put("payStatus", 1);
                mapEarnings.put("payStatusNew", 2);
                goodsService.updateGoodsAddedEarnings(mapEarnings);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(-500, "违规操作！");
            }

        } else {
            return ResultUtil.error(-500, "订单已完成,请勿重复操作");
        }


    }

    /**
     * @param map
     * @description: 取消订单
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/12 17:13
     */
    @RequestMapping("cancelOrder")
    public Result cancelOrder(@RequestBody Map<String, Object> map)  {
        Map<String, Object> mapOrder = service.getById(map);
        if (mapOrder.get("status").toString().equals("1") ||
                mapOrder.get("status").toString().equals("2")) {
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", mapOrder.get("id"));
            mapNew.put("status", "4");
            mapNew.put("goodsId", mapOrder.get("goodsId"));
            service.updateNew(mapNew);

            return ResultUtil.success();
        } else {
            return ResultUtil.error(-500, "该状态不允许取消订单");
        }
    }

}
